package com.example.nfcschool;

import java.io.FileInputStream;
import java.lang.reflect.Method;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.util.Log;
import android.widget.Toast;

public class Receiver extends BroadcastReceiver {
	Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		this.context = context;
		String check1="";
		String IntentAction = intent.getAction();
		
		FileInputStream fis = null;
		try{
			if(context.openFileInput("networkcheck") != null){
				
			fis = context.openFileInput("networkcheck");
			byte[] data2 = new byte[fis.available()];
			fis.read(data2);
			
			check1 = new String(data2);
			fis.close();}
		}catch(Exception ex){
			Log.e("파일 load 에러",ex.toString());
		}	
		
		if(check1.equals("false")){	
			
		}
		else if(check1.equals("true")){
			if (IntentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				DisconnectDATA();
				toggleWiFi(false);
			}
		}else{
			if (IntentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				DisconnectDATA();
				toggleWiFi(false);
			}
		}

		
	}

	public void DisconnectDATA() {

		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(context.getApplicationContext().CONNECTIVITY_SERVICE);

		try {
			Class localClass = connectivityManager.getClass();

			Class[] arrayOfClass = new Class[1];

			arrayOfClass[0] = Boolean.TYPE;

			Method localMethod = localClass.getMethod("setMobileDataEnabled",
					arrayOfClass);

			ConnectivityManager localConnectivityManager = connectivityManager;

			Object[] arrayOfObject = new Object[1];

			arrayOfObject[0] = Boolean.valueOf(false);

			localMethod.invoke(localConnectivityManager, arrayOfObject);
			toggleWiFi(false);

		}

		catch (Exception e) {

			e.printStackTrace();

		}

	}

	public void toggleWiFi(boolean status) {
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		wifiManager.setWifiEnabled(false);
	}
}
